# core/page_manager.py
from PySide6.QtWidgets import QStackedWidget

class PageManager:
    """页面管理器，负责页面注册和切换"""
    def __init__(self, event_bus):
        self.event_bus = event_bus
        self.main_pages = {}  # 主页面映射：page_id → 页面组件
        self.sub_stacks = {}  # 子页面栈映射：stack_id → QStackedWidget
        self.sub_pages = {}   # 子页面映射：page_path → (stack_id, 索引)
        
        # 连接事件总线信号
        self.event_bus.switch_sub_page.connect(self.switch_sub_page)
    
    def register_main_page(self, page_id, page_widget):
        """注册主页面到管理器"""
        self.main_pages[page_id] = page_widget
        print(f"注册主页面: {page_id}")
    
    def register_sub_stack(self, stack_id, stack_widget):
        """注册子页面栈到管理器"""
        self.sub_stacks[stack_id] = stack_widget
        print(f"注册子栈: {stack_id}")
    
    def register_sub_page(self, page_path, stack_id, page_widget):
        """注册子页面到指定子栈"""
        if stack_id not in self.sub_stacks:
            raise ValueError(f"子栈 {stack_id} 未注册")
            
        stack = self.sub_stacks[stack_id]
        index = stack.addWidget(page_widget)
        self.sub_pages[page_path] = (stack_id, index)
        print(f"注册子页面: {page_path} → 子栈 {stack_id}, 索引 {index}")
    
    def switch_sub_page(self, page_path):
        """通过路径切换子页面"""
        if page_path not in self.sub_pages:
            print(f"错误: 子页面 {page_path} 未注册")
            return
            
        stack_id, index = self.sub_pages[page_path]
        self.sub_stacks[stack_id].setCurrentIndex(index)


    # 在 PageManager 类中添加
    def push_page(self, stack, page_widget):
        """向栈中添加页面"""
        stack.addWidget(page_widget)
        stack.setCurrentIndex(stack.count() - 1)
        print(f"页面入栈，当前栈深度: {stack.count()}")

    def pop_page(self, stack):
        """从栈中移除当前页面"""
        if stack.count() > 1:
            current_widget = stack.currentWidget()
            stack.removeWidget(current_widget)
            current_widget.deleteLater()
            stack.setCurrentIndex(stack.count() - 1)
            print(f"页面出栈，当前栈深度: {stack.count()}")
        else:
            print("栈已空，无法继续出栈")

    def clear_stack(self, stack):
        """清空栈中所有页面（修正版，适配 QStackedWidget）"""
        # 从最后一个部件开始移除（避免索引变化导致的问题）
        while stack.count() > 0:
            # 获取当前栈中最后一个部件
            widget = stack.widget(stack.count() - 1)
            # 从栈中移除并销毁部件
            stack.removeWidget(widget)
            widget.deleteLater()
        print("栈已清空")